package xyz.ag.Servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.ag.Beans.Menu;
import xyz.ag.Beans.User;
import xyz.ag.Service.BookServiceInterface;
import xyz.ag.Service.impl.BookServiceInterfaceImpl;
import xyz.ag.Service.impl.UserServiceInterfaceImpl;

/**
 * Servlet implementation class initIndexServlet
 */
/**
 * 首页初始化Servlet
 * @author User
 *
 */
@WebServlet("/")
public class initIndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 覆盖service方法 来实现效果
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		/*准备首页数据*/
		BookServiceInterface bookSI = new BookServiceInterfaceImpl();
		ArrayList<Menu> ificationlist =  bookSI.getAllification();
		req.getSession().setAttribute("rigthlist", ificationlist);
		req.getRequestDispatcher("myindex.jsp").forward(req, resp);
		/*准备主体推荐数据*/
		
		
		/**
		 * 遍历Cookie 检查用户是否存在短时间重新登录
		 */
		String user = "";
		String password = "";
		Cookie[] Cookies = req.getCookies();
		System.out.println("尝试获取cookie");
        for(int a=0;a<Cookies.length;a++){
            if(Cookies[a].getName().contains("mufengbook")) {
                 user = Cookies[a].getName().split("mufengbook")[1];
                 System.out.println(Cookies[a].getValue());
                 password = Cookies[a].getValue();
                 System.out.println("user="+user+" password = "+password);
            }
            User userb = new User.Builder().userName(user).userPassword(password).build();
            if(new UserServiceInterfaceImpl().UserLogin(userb)){
            	System.out.println("cookie认证成功");
            	req.getSession().setAttribute("user", userb);//设置用户对象
            }
            
        }
        System.out.println("cookie获取结束");
	}
       
    

}
